/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.zx.mockexam.special.picture.service;

import java.util.List;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.ServiceException;
import com.jeesite.common.service.TreeService;
import com.jeesite.common.utils.excel.ExcelImport;
import com.jeesite.common.validator.ValidatorUtils;
import com.jeesite.modules.zx.mockexam.special.picture.entity.TmockexamSpecialPicture;
import com.jeesite.modules.zx.mockexam.special.single.entity.TmockexamSpecialSingle;
import com.jeesite.modules.zx.mockexam.special.multiple.entity.TMockeSpecialMultiple;
import com.jeesite.modules.zx.mockexam.special.picture.dao.TmockexamSpecialPictureDao;
import com.jeesite.modules.file.utils.FileUploadUtils;
import com.jeesite.modules.sys.entity.Post;
import com.jeesite.modules.sys.service.PostService;
import com.jeesite.modules.sys.utils.DictUtils;

/**
 * 模拟-专项考试-图片题表Service
 * @author zpp
 * @version 2020-02-08
 */
@Service
@Transactional(readOnly=true)
public class TmockexamSpecialPictureService extends TreeService<TmockexamSpecialPictureDao, TmockexamSpecialPicture> {
	@Autowired
	private PostService postService;
	/**
	 * 获取单条数据
	 * @param tmockexamSpecialPicture
	 * @return
	 */
	@Override
	public TmockexamSpecialPicture get(TmockexamSpecialPicture tmockexamSpecialPicture) {
		return super.get(tmockexamSpecialPicture);
	}
	
	/**
	 * 查询列表数据
	 * @param tmockexamSpecialPicture
	 * @return
	 */
	@Override
	public List<TmockexamSpecialPicture> findList(TmockexamSpecialPicture tmockexamSpecialPicture) {
		return super.findList(tmockexamSpecialPicture);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param tmockexamSpecialPicture
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(TmockexamSpecialPicture tmockexamSpecialPicture) {
		super.save(tmockexamSpecialPicture);
		// 保存上传图片
		FileUploadUtils.saveFileUpload(tmockexamSpecialPicture.getId(), "tmockexamSpecialPicture_image");
		// 保存上传附件
		FileUploadUtils.saveFileUpload(tmockexamSpecialPicture.getId(), "tmockexamSpecialPicture_file");
	}
	
	/**
	 * 更新状态
	 * @param tmockexamSpecialPicture
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(TmockexamSpecialPicture tmockexamSpecialPicture) {
		super.updateStatus(tmockexamSpecialPicture);
	}
	
	/**
	 * 删除数据
	 * @param tmockexamSpecialPicture
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(TmockexamSpecialPicture tmockexamSpecialPicture) {
		super.delete(tmockexamSpecialPicture);
	}
	@Transactional(readOnly=false)
	public String importData(MultipartFile file, boolean isUpdateSupport) {
		if (file == null){
			throw new ServiceException(text("请选择导入的数据文件！"));
		}
		int successNum = 0; int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		
		try(ExcelImport ei = new ExcelImport(file, 2, 0)){
			List<TmockexamSpecialPicture> list = ei.getDataList(TmockexamSpecialPicture.class);
			for (TmockexamSpecialPicture entity : list) {
				try{
					if(StringUtils.isBlank(entity.getParentCode())){
						continue;
					}
					String strExplain = entity.getStrExplain();
					if(StringUtils.isNotBlank(strExplain)){
						String objExplain=DictUtils.getDictValue("t_reading_explain", strExplain, null);
						if(StringUtils.isNotBlank(objExplain)){
							entity.setObjExplain(Integer.parseInt(objExplain));
						}
					}
					String categoryName=entity.getCategoryName();
					if(StringUtils.isNotBlank(categoryName)){
						String category=DictUtils.getDictValue("t_examination_category", categoryName, null);
						if(StringUtils.isNotBlank(category)){
							entity.setCategory(Integer.parseInt(category));
						}
					}
					String postName=entity.getPostName();
					if(StringUtils.isNotBlank(postName)){
						Post post= new Post();
						post.setPostName(postName);
						List<Post> findList = postService.findList(post);
						if(findList!=null&&findList.size()>0){
						  entity.setPost(findList.get(0).getPostCode());
						}
					}
					String difficultyName=entity.getDifficultyName();
					if(StringUtils.isNotBlank(difficultyName)){
						String difficulty=DictUtils.getDictValue("t_degree_difficulty", difficultyName, null);
						if(StringUtils.isNotBlank(difficulty)){
							entity.setDifficulty(Integer.parseInt(difficulty));
						}
					}
					String knowledgePointName = entity.getKnowledgePointName();
					if(StringUtils.isNotBlank(knowledgePointName)){
						String knowledgePointType=DictUtils.getDictValue("t_knowledge_point_type", knowledgePointName, null);
						if(StringUtils.isNotBlank(knowledgePointType)){
							entity.setKnowledgePointType(Integer.parseInt(knowledgePointType));
						}
					}
					// 验证数据文件
					ValidatorUtils.validateWithException(entity);
					// 验证是否存在这个用户
					TmockexamSpecialPicture u = get(entity.getId());
					if(StringUtils.isBlank(entity.getId())){
						if (StringUtils.isNotBlank(entity.getParentCode())){
							entity.setParent(this.get(entity.getParentCode()));
						}
						TmockexamSpecialPicture where = new TmockexamSpecialPicture();
						where.setParentCode(entity.getParentCode());
						TmockexamSpecialPicture last = this.getLastByParentCode(where);
						if (last != null){
							entity.setTreeSort(last.getTreeSort() + 30);
							entity.setId(IdGen.nextCode(last.getId()));
						}else if (entity.getParent() != null){
							entity.setId(entity.getParent().getId() + "001");
						}
					}
					if (u == null){
						entity.setIsNewRecord(true);
						this.save(entity);
						successNum++;
						successMsg.append("<br/>" + successNum + "、账号 " + entity.getId() + " 导入成功");
					} else if (isUpdateSupport){
						entity.setId(u.getId());
						this.save(entity);
						successNum++;
						successMsg.append("<br/>" + successNum + "、账号 " + entity.getId() + " 更新成功");
					} else {
						failureNum++;
						failureMsg.append("<br/>" + failureNum + "、账号 " + entity.getId() + " 已存在");
					}
				} catch (Exception e) {
					failureNum++;
					String msg = "<br/>" + failureNum + "、账号 " + entity.getId() + " 导入失败：";
					if (e instanceof ConstraintViolationException){
						ConstraintViolationException cve = (ConstraintViolationException)e;
						for (ConstraintViolation<?> violation : cve.getConstraintViolations()) {
							msg += Global.getText(violation.getMessage()) + " ("+violation.getPropertyPath()+")";
						}
					}else{
						msg += e.getMessage();
					}
					failureMsg.append(msg);
					logger.error(msg, e);
				}
			}
		} catch (Exception e) {
			failureMsg.append(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new ServiceException(failureMsg.toString());
		}else{
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}
	
}